package com.atguigu.spring.controller;

import com.atguigu.spring.entity.User;
import jakarta.validation.Valid;
import jakarta.validation.constraints.Max;
import jakarta.validation.constraints.Min;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Pattern;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@RestController
public class DemoController {

    @RequestMapping("/save/user")
    public List<String> test01(@Valid @RequestBody User user, BindingResult result) {

        if (result.hasErrors()) {
            return result.getFieldErrors()
                    .stream()
                    .map(fieldError -> {
                        String fieldName = fieldError.getField();
                        Object rejectedValue = fieldError.getRejectedValue();
                        String defaultMessage = fieldError.getDefaultMessage();

                        return "字段名称：" + fieldName + "， 输入数据：" + rejectedValue + "， 提示信息：" + defaultMessage;
                    })
                    .collect(Collectors.toList());
        }

        return Arrays.asList(user.toString());
    }

    @Validated
    @RequestMapping("/send/age")
    public String test02(@NotNull @Min(value = 18) @Max(value = 65) @RequestParam("age") Integer age) {
        return "age = " + age;
    }

    @Validated
    @RequestMapping("/get/param")
    public String getParam(
            @Pattern(regexp = "^[A-Za-z_][A-Za-z_0-9]{4,8}$") @RequestParam("userName") String userName,
            @Pattern(regexp = "^[A-Za-z_0-9]{5,9}$")  @RequestParam("userPwd") String userPwd) {

        return "ok userName = " + userName + " userPwd = " + userPwd;
    }

}
